package com.azt.front.action.order;

import com.alibaba.fastjson.JSON;
import com.azt.api.dto.*;
import com.azt.api.dto.QuoteOrder.QuoteOrderDetail;
import com.azt.api.dto.QuoteOrder.QuoteOrderDetail.QuoteOrderItem;
import com.azt.api.enums.*;
import com.azt.api.pojo.*;
import com.azt.api.service.*;
import com.azt.exception.BaseException;
import com.azt.exception.NoPermissionException;
import com.azt.front.action.BaseAction;
import com.azt.front.permission.ClearRequire;
import com.azt.front.permission.RequireCompany;
import com.azt.front.utils.ContextUtil;
import com.azt.front.utils.Globals;
import com.azt.model.*;
import com.azt.provider.mapper.OrderShipProductMapper;
import com.azt.provider.mapper.PinganPayMapper;
import com.azt.utils.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xiaoleilu.hutool.convert.Convert;
import com.xiaoleilu.hutool.util.CollectionUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.WebUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

import static com.alibaba.fastjson.JSON.parseArray;

/**
 * ┌───┐   ┌───┬───┬───┬───┐ ┌───┬───┬───┬───┐ ┌───┬───┬───┬───┐ ┌───┬───┬───┐
 * │Esc│   │ F1│ F2│ F3│ F4│ │ F5│ F6│ F7│ F8│ │ F9│F10│F11│F12│ │P/S│S L│P/B│  ┌┐    ┌┐    ┌┐
 * └───┘   └───┴───┴───┴───┘ └───┴───┴───┴───┘ └───┴───┴───┴───┘ └───┴───┴───┘  └┘    └┘    └┘
 * ┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───────┐ ┌───┬───┬───┐ ┌───┬───┬───┬───┐
 * │~ `│! 1│@ 2│# 3│$ 4│% 5│^ 6│& 7│* 8│( 9│) 0│_ -│+ =│ BacSp │ │Ins│Hom│PUp│ │N L│ / │ * │ - │
 * ├───┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─────┤ ├───┼───┼───┤ ├───┼───┼───┼───┤
 * │ Tab │ Q │ W │ E │ R │ T │ Y │ U │ I │ O │ P │{ [│} ]│ | \ │ │Del│End│PDn│ │ 7 │ 8 │ 9 │   │
 * ├─────┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴─────┤ └───┴───┴───┘ ├───┼───┼───┤ + │
 * │ Caps │ A │ S │ D │ F │ G │ H │ J │ K │ L │: ;│" '│ Enter  │               │ 4 │ 5 │ 6 │   │
 * ├──────┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴────────┤     ┌───┐     ├───┼───┼───┼───┤
 * │ Shift  │ Z │ X │ C │ V │ B │ N │ M │< ,│> .│? /│  Shift   │     │ ↑ │     │ 1 │ 2 │ 3 │   │
 * ├─────┬──┴─┬─┴──┬┴───┴───┴───┴───┴───┴──┬┴───┼───┴┬────┬────┤ ┌───┼───┼───┐ ├───┴───┼───┤ E││
 * │ Ctrl│    │Alt │         Space         │ Alt│    │    │Ctrl│ │ ← │ ↓ │ → │ │   0   │ . │←─┘│
 * └─────┴────┴────┴───────────────────────┴────┴────┴────┴────┘ └───┴───┴───┘ └───────┴───┴───┘
 */
@Controller
@RequireCompany
@RequestMapping("/order")
public class OrderAction extends BaseAction {

	@Autowired
	private OrderService orderService;

	@Autowired
	private CompanyService companyService;

	@Autowired
	private UserService userService;

	@Autowired
	private OrderPayService orderPayService;

    @Autowired
    private OrderShipService orderShipService;

    @Autowired
    private DeliveryService deliveryService;

	@Autowired
	private EnqEnquiryService enquiryService;

	@Autowired
	private EnqQuoteService quoteService;

	@Autowired
	private AddressService addressService;

	@Autowired
	private OrderShipProductMapper orderShipProductMapper;

    @Autowired
    private AreaService areaService;

	@Autowired
	private MsgConfigService msgConfigService;

	@Autowired
	private ProductService productService;

	@Autowired
	private CompanySignService companySignService;

	@Autowired
	private DictionaryService dictionaryService;

	@Autowired
	private PinganAccountService pinganAccountService;

	@Autowired
	private CoinService coinService;

	@Autowired
	private IntegralService integralService;

	@Autowired
	private GiftService giftService;

	@ClearRequire
	@RequestMapping(value = "/address")
	public String loadAddress(Model model) {
		boolean all = getParaToBool("all", false);	//是否显示全部
		model.addAttribute("addressList", addressService.findUserAddress(ContextUtil.getUserId()));
		model.addAttribute("all", all);
		return "order/address";
	}

	/**
	 * 载入询价下单页面<br>
	 * 参数： enquiryId=xx&item=[{quoteId:xx,items:[itemId:xx,quantity:xx]}, {quoteId:xx,items:[itemId:xx,quantity:xx]}]
	 * */
	@RequestMapping(value = "/submit/quote")
	public String loadSubmitQuoteOrder(Model model) {
		Integer enquiryId = getParaToInt("enquiryId");		//询价id
		String item = getPara("item");

		if(enquiryId == null || StrUtil.isBlank(item)) {
			//订单数据错误
		}
		List<QuoteOrderDetail> detailList = parseArray(item, QuoteOrderDetail.class);
		if(detailList == null || detailList.size() <= 0) {
			//订单数据错误
		}

		List<Map> list = new ArrayList<>();
		EnqEnquiry enquiry = enquiryService.getEnquiryById(enquiryId);
		double totalPrice = 0;
		for(QuoteOrderDetail orderDetail : detailList) {
			Map map = new HashMap();
			Integer quoteId = orderDetail.getQuoteId();					//报价id
			EnqQuote quote = enquiryService.getEnqQuoteById(quoteId);
			map.put("quote", quote);
			List<Map> _list = new ArrayList<>();
			List<QuoteOrderItem> itemList = orderDetail.getItems();		//产品
			double orderPrice = 0;
			for(QuoteOrderItem orderItem : itemList) {
				Integer itemId = orderItem.getItemId();					//报价产品id
				Double quantity = orderItem.getQuantity();				//下单数量

				EnqQuoteItem quoteItem = quoteService.getQuoteItemById(itemId);
				double itemPrice = MathUtil.multiply(quoteItem.getUnitprice(), quantity, 2);

				Map m = new HashMap();
				m.put("quoteItem", quoteItem);
				m.put("quantity", quantity);
				m.put("itemPrice", itemPrice);
				_list.add(m);
				orderPrice = MathUtil.add(orderPrice, itemPrice);
			}
			map.put("itemList", _list);
			map.put("orderPrice", MathUtil.round(orderPrice, 2));		//该订单的金额
			list.add(map);

			totalPrice = MathUtil.add(totalPrice, orderPrice);		//所有订单的金额
		}

		//收货地址(默认地址是第一个)
		List<Address> addressList = addressService.findUserAddress(ContextUtil.getUserId());
		//获取公司基本户
		Company topCompany = companyService.getTopParentCompany(ContextUtil.getCompany().getId());
		List<CompanyBank> companyBankList = companyService.findCompanyBankByCid(topCompany.getId(), 2);
		CompanyBank companyBank = CollectionUtil.isNotEmpty(companyBankList) ? companyBankList.get(0) : new CompanyBank();

        CompanyInfo companyInfo = companyService.selectByCompanyIdDetail(topCompany.getId());

		model.addAttribute("topCompany", topCompany);
        model.addAttribute("companyBank", companyBank);
        model.addAttribute("companyInfo", companyInfo);
        model.addAttribute("enquiry", enquiry);
        model.addAttribute("addressList", addressList);
		model.addAttribute("list", list);
		model.addAttribute("totalPrice", MathUtil.round(totalPrice, 2));
		model.addAttribute("CommonUtil", FreemarkerUtils.getStaticModel(CommonUtil.class));
		return "order/submitQuoteOrder";
	}

	/**
	 * 载入商品下单页面<br>
	 * 参数： data=[{skuId: xx, quantity: xx}, ...]
	 * */
	@ClearRequire
	@RequireCompany(noState = {Company.AUDIT_STATE_INIT, Company.AUDIT_STATE_NO})
	@RequestMapping(value = "/submit/product")
	public String loadSubmitProductOrder(Model model) {
		String data = getParaTrim("data");

		if(StrUtil.isBlank(data)) {
			//订单数据错误
		}

		List<Map> dataList = JSON.parseArray(data, Map.class);
		if(CollectionUtil.isEmpty(dataList)) {
			//订单数据错误
		}

		boolean isSigned = companySignService.getCompanySign(ContextUtil.getCompanyId(), 2, true) != null;
		List<CartListData> cartListDatas = productService.parseCartData(dataList, isSigned);

		//获取公司基本户
		Company topCompany = companyService.getTopParentCompany(ContextUtil.getCompany().getId());
		List<CompanyBank> companyBankList = companyService.findCompanyBankByCid(topCompany.getId(), 2);
		CompanyBank companyBank = CollectionUtil.isNotEmpty(companyBankList) ? companyBankList.get(0) : new CompanyBank();
		CompanyInfo companyInfo = companyService.selectByCompanyIdDetail(topCompany.getId());

		CompanySign companySign = companySignService.getCompanySign(ContextUtil.getCompanyId(), 2, true);	//是否是签约用户
		model.addAttribute("isSigned", companySign != null);
		model.addAttribute("topCompany", topCompany);
		model.addAttribute("companyBank", companyBank);
		model.addAttribute("companyInfo", companyInfo);
		model.addAttribute("list", cartListDatas);
		model.addAttribute("CommonUtil", FreemarkerUtils.getStaticModel(CommonUtil.class));
		
		
		return "order/submitProductOrder";
	}

	/**
	 * 提交询价订单
	 * */
	@ResponseBody
	@RequestMapping(value = "/submitQuoteOrder", method = RequestMethod.POST)
	public AjaxJson submitQuoteOrder() {
		LOGGER.info(ContextUtil.getUser().getRealName() + "开始提交询价订单");

		Integer addressId = getParaToInt("addressId");	//收货地址id
		Integer invoice = getParaToInt("invoice");	//发票类型
		String taxTitle = getPara("taxTitle");         //发票抬头
		String taxNumber = getPara("taxNumber");       //税号
		String taxAddress = getPara("taxAddress");         //注册地址
		String taxPhone = getPara("taxPhone");             //注册电话
		String taxOpenbank = getPara("taxOpenbank");      //开户银行
		String taxBankNumber = getPara("taxBankNumber");   //开户帐号
		String data = getPara("data");     //封装了订单数据的json,格式：[{quoteId:xx, message:xx, items:[{itemId:xx, quantity:xx}]},{....}]

		QuoteOrder quoteOrder = new QuoteOrder();
		try {
			quoteOrder.setAddressId(addressId);
			quoteOrder.setInvoice(invoice);
			quoteOrder.setTaxTitle(taxTitle);
			quoteOrder.setTaxNumber(taxNumber);
			quoteOrder.setTaxAddress(taxAddress);
			quoteOrder.setTaxPhone(taxPhone);
			quoteOrder.setTaxOpenbank(taxOpenbank);
			quoteOrder.setTaxBankNumber(taxBankNumber);
			List<QuoteOrderDetail> detailList = parseArray(data, QuoteOrderDetail.class);
			quoteOrder.setData(detailList);
		} catch (Exception e) {
            LOGGER.error("parse order request data error", e);
			return AjaxJson.error("订单数据错误");
		}
		try {
			List<OrderInfo> orderList = orderService.submitQuoteOrder(quoteOrder, ContextUtil.getUser());

            StringBuilder sb = new StringBuilder();
            for(OrderInfo order : orderList) {
                sb.append(order.getId()).append(",");
            }
            if(sb.toString().endsWith(",")) {
                sb = sb.deleteCharAt(sb.length() - 1);
            }
            AjaxJson aj = AjaxJson.success();
            aj.setObj(sb.toString());
			return aj;
		} catch (BaseException be) {
			return AjaxJson.error(be.getErrorCode());
		} catch (Exception e) {
            LOGGER.error("submit quote order error", e);
			return AjaxJson.error("操作失败");
		}
	}

	/**
	 * 提交商品订单
	 * */
	@ClearRequire
	@RequireCompany(noState = {Company.AUDIT_STATE_INIT, Company.AUDIT_STATE_NO})
	@ResponseBody
	@RequestMapping(value = "/submitProductOrder", method = RequestMethod.POST)
	public AjaxJson submitProductOrder() {
		LOGGER.info(ContextUtil.getUser().getRealName() + "开始提交商品订单");

		Integer addressId = getParaToInt("addressId");	//收货地址id
		Integer invoice = getParaToInt("invoice");	//发票类型
		String taxTitle = getPara("taxTitle");         //发票抬头
		String taxNumber = getPara("taxNumber");       //税号
		String taxAddress = getPara("taxAddress");         //注册地址
		String taxPhone = getPara("taxPhone");             //注册电话
		String taxOpenbank = getPara("taxOpenbank");      //开户银行
		String taxBankNumber = getPara("taxBankNumber");   //开户帐号
		String data = getPara("data");     //封装了订单数据的json,格式：[{companyId:xx, message:xx, items:[{skuId:xx, quantity:xx}]},{....}]

		List<ProductOrder.ProductOrderDetail> detailList = new ArrayList<>();
		ProductOrder productOrder = new ProductOrder();
		try {
			productOrder.setAddressId(addressId);
			productOrder.setInvoice(invoice);
			productOrder.setTaxTitle(taxTitle);
			productOrder.setTaxNumber(taxNumber);
			productOrder.setTaxAddress(taxAddress);
			productOrder.setTaxPhone(taxPhone);
			productOrder.setTaxOpenbank(taxOpenbank);
			productOrder.setTaxBankNumber(taxBankNumber);
			detailList = parseArray(data, ProductOrder.ProductOrderDetail.class);
			productOrder.setData(detailList);
		} catch (Exception e) {
			LOGGER.error("parse order request data error", e);
			return AjaxJson.error("订单数据错误");
		}
		try {
			List<OrderInfo> orderList = orderService.submitProductOrder(productOrder, ContextUtil.getUser());

			//删除购物车对应的商品
			List<Map> cartList = ContextUtil.getCartCookie();
			if(CollectionUtil.isNotEmpty(cartList)) {
				Iterator<Map> iterator = cartList.iterator();
				while (iterator.hasNext()) {
					Map cart = iterator.next();
					Integer skuId = Convert.toInt(cart.get("skuId"));
					Integer quantity = Convert.toInt(cart.get("quantity"));
					if(skuId != null && quantity != null) {

						for(ProductOrder.ProductOrderDetail detail : detailList) {
							for(ProductOrder.ProductOrderDetail.ProductOrderItem item : detail.getItems()) {
								Integer _skuId = item.getSkuId();
								if(_skuId != null && skuId.intValue() == _skuId.intValue()) {
									//删除该skuId
									iterator.remove();
									continue;
								}
							}
						}

					}
				}
			}
			ContextUtil.setCartCookie(cartList);

			StringBuilder sb = new StringBuilder();
			for(OrderInfo order : orderList) {
				sb.append(order.getId()).append(",");
			}
			if(sb.toString().endsWith(",")) {
				sb = sb.deleteCharAt(sb.length() - 1);
			}
			AjaxJson aj = AjaxJson.success();
			aj.setObj(sb.toString());
			return aj;
		} catch (BaseException be) {
			return AjaxJson.error(be.getErrorCode());
		} catch (Exception e) {
			LOGGER.error("submit quote order error", e);
			return AjaxJson.error("操作失败");
		}
	}

	/**
     * 询价下单成功页面
     * */
	@RequestMapping(value = "/quote/success")
	public String quoteSuccess(Model model) {
        String ids = getPara("id");

        if(StrUtil.isNotBlank(ids)) {
            OrderInfo _order = null;
            List<Map> orderList = new ArrayList<>();
            double totalPrice = 0;

            String[] array = ids.split(",");
            for (String str : array) {
                Integer orderId = Convert.toInt(str);
                if(orderId != null) {
                    OrderInfo order = orderService.getOrderInfoById(orderId);
                    if(order != null) {
                        _order = _order == null ? order : _order;
                        double orderPrice = order.getTotalPrice();
                        totalPrice = MathUtil.add(orderPrice, totalPrice);
                        Company sellerCompany = companyService.getCompanyById(order.getSellerCompanyId());

                        Map m = new HashMap();
                        m.put("orderId", order.getId());
                        m.put("orderNumber", order.getOrderNumber());
                        m.put("orderPrice", order.getTotalPrice());
                        m.put("sellerCompanyName", sellerCompany.getCompanyName());
                        orderList.add(m);
                    }
                }
            }

			EnqEnquiry enquiry = enquiryService.getEnquiryById(_order.getEnquiryId());
            Area province = areaService.getAreaByCode(_order.getReceiptProvince());
            Area city = areaService.getAreaByCode(_order.getReceiptCity());
            Area area = areaService.getAreaByCode(_order.getReceiptArea());

            model.addAttribute("orderList", orderList);
            model.addAttribute("ordertime", _order.getOrdertime());
			model.addAttribute("enquiry", enquiry);
            model.addAttribute("totalPrice", totalPrice);
            model.addAttribute("address", (province != null ? province.getName() : "") + (city != null ? city.getName() : "") + (area != null ? area.getName() : "") + _order.getReceiptAddress());
            model.addAttribute("receiptName", _order.getReceiptName());
            model.addAttribute("receiptPhone", StrUtil.isNotBlank(_order.getReceiptTel()) ? _order.getReceiptTel() : _order.getReceiptPhone());
        }

        return "order/quoteSuccess";
    }

	/**
	 * 商品下单成功页面
	 * */
	@ClearRequire
	@RequireCompany(noState = {Company.AUDIT_STATE_INIT, Company.AUDIT_STATE_NO})
	@RequestMapping(value = "/product/success")
	public String productSuccess(Model model) {
		String ids = getPara("id");

		if(StrUtil.isNotBlank(ids)) {
			OrderInfo _order = null;
			List<Map> orderList = new ArrayList<>();
			double totalPrice = 0;

			String[] array = ids.split(",");
			for (String str : array) {
				Integer orderId = Convert.toInt(str);
				if(orderId != null) {
					OrderInfo order = orderService.getOrderInfoById(orderId);
					if(order != null) {
						_order = _order == null ? order : _order;
						double orderPrice = order.getTotalPrice();
						totalPrice = MathUtil.add(orderPrice, totalPrice);
						Company sellerCompany = companyService.getCompanyById(order.getSellerCompanyId());

						Map m = new HashMap();
						m.put("orderId", order.getId());
						m.put("orderNumber", order.getOrderNumber());
						m.put("orderPrice", order.getTotalPrice());
						m.put("sellerCompanyName", sellerCompany.getCompanyName());
						orderList.add(m);
					}
				}
			}

			Area province = areaService.getAreaByCode(_order.getReceiptProvince());
			Area city = areaService.getAreaByCode(_order.getReceiptCity());
			Area area = areaService.getAreaByCode(_order.getReceiptArea());

			model.addAttribute("orderList", orderList);
			model.addAttribute("ordertime", _order.getOrdertime());
			model.addAttribute("totalPrice", totalPrice);
			model.addAttribute("address", (province != null ? province.getName() : "") + (city != null ? city.getName() : "") + (area != null ? area.getName() : "") + _order.getReceiptAddress());
			model.addAttribute("receiptName", _order.getReceiptName());
			model.addAttribute("receiptPhone", StrUtil.isNotBlank(_order.getReceiptTel()) ? _order.getReceiptTel() : _order.getReceiptPhone());
		}

		return "order/productSuccess";
	}

	/**
	 * 载入询价订单列表<br>
	 * 管理员：可以查看本公司以及分公司的所有订单<br>
	 * 普通员工：只能查看自己的订单
	 * */
	@RequestMapping(value = "/quote", method = RequestMethod.GET)
	public String listQuoteOrder(Model model) {
		int tab = getParaToInt("tab", 0);		//tab标签：0.全部订单 1.待付款  2.已付款  3.已发货  10.分公司订单
		int pageNo = getParaToInt("pageNo", 1);   //页码
		int pageSize = Globals.PAGESIZE;	//每页显示订单数
		String keyword = getParaTrim("keyword");	//关键字
		String sellerCompanyName = getParaTrim("sellerCompanyName");	//卖家名称
		String buyerCompanyName = getParaTrim("buyerCompanyName");	//买家名称
		Integer state = getParaToInt("state");	//订单状态（查询用）
		Date sdate = getParaToDate("sdate");	//开始日期
		Date edate = getParaToDate("edate");	//结束日期

		int currentRoleType = ContextUtil.getCurrentRoleType();
		User currentUser = ContextUtil.getUser();
		Company currentCompany = ContextUtil.getCompany();
		boolean isAdmin = ContextUtil.isAdmin();

        boolean showChildCompanyTab = false;    //只有当前登录人是管理员且有分公司的时候才显示分公司的标签
		//构造查询参数
		Map param = new HashMap();
		param.put("keyword", keyword);
		param.put("sellerCompanyName", sellerCompanyName);
		param.put("buyerCompanyName", buyerCompanyName);
        param.put("state", state);
        param.put("sdate", sdate);
		if(edate != null) {
			param.put("edate", DateUtils.addDays(edate, 1));
		}

		List<Company> childCompanyList = null;
		List<UserEnum> userenum = new ArrayList<>();
		userenum.add(UserEnum.cfinance);
		boolean isFinance = userService.getUserAuthorityByUserId(currentUser.getId(), userenum);	//是否是财务
		boolean adminOrfinance = isAdmin || isFinance;		//是否是管理员或财务
		if(ContextUtil.isPurchaser()) {
			//采购商
			if(isAdmin || isFinance) {
                childCompanyList = companyService.findAllChildCompany(currentCompany.getId());  //分公司
                if(childCompanyList != null && childCompanyList.size() > 0) {
                    showChildCompanyTab = true;
                }
				//管理员及财务：可以查看本公司的所有订单以及分公司的订单
                if(tab == 10) {
                    //查看分公司的订单
                    if(childCompanyList != null && childCompanyList.size() > 0) {
                        param.put("buyerCompanys", childCompanyList);
                    } else {
                        param.put("buyerCompanyId", -1);    //传入一个不存在的公司id，查询无结果
                    }
                } else {
                    //查看本公司的订单
                    param.put("buyerCompanyId", currentCompany.getId());
                }
			} else {
				//普通员工：只能查看自己的订单
				param.put("buyerUserId", currentUser.getId());
			}
		} else if(ContextUtil.isProvider()) {
			//供应商
			if(isAdmin || isFinance) {
				//管理员及财务：可以查看本公司的所有订单
				param.put("sellerCompanyId", currentCompany.getId());
			} else {
				//普通员工：只能查看自己的订单
				param.put("sellerUserId", currentUser.getId());
			}
		}


		PageHelper.startPage(pageNo, pageSize);
		List<Map> orderList = orderService.searchQuoteOrder(param);

		for(Map order : orderList) {
			Integer buyerCompanyId = Convert.toInt(order.get("buyerCompanyId"));
			Integer buyerParentId = Convert.toInt(order.get("buyerParentId"));
			if(buyerCompanyId != null && buyerParentId != null) {
				//分公司
				Company topCompany = companyService.getTopParentCompany(buyerCompanyId);
				if(topCompany != null) {
					order.put("topCompanyName", topCompany.getCompanyName());
				}
			}
			Double detailQuantity = Convert.toDouble(order.get("detailQuantity"));
			Double shipQuantity = Convert.toDouble(order.get("shipQuantity"));
			order.put("isShipEnd", detailQuantity.doubleValue() == shipQuantity.doubleValue());
			List<OrderPayInfo> orderPay = orderPayService.findOrderPay(Convert.toInt(order.get("id")), OrderPayResultEnum.SUBMIT.getValue(), OrderPayResultEnum.REVIEW.getValue(), OrderPayResultEnum.SUCCESS.getValue());
			order.put("paidSize", orderPay.size());
		}

		model.addAttribute("orderList", orderList);
        model.addAttribute("page", new PageInfo(orderList));
        model.addAttribute("orderStateMap", CommonUtil.getEnumMap(OrderStateEnum.class));   //交易状态
		//待付款订单数量(本公司)
		int unPayOrderCount = orderService.getMyQuoteOrderCount(currentRoleType, isAdmin, currentCompany, currentUser, OrderStateEnum.UNPAY.getValue(), false);
		//已付款订单数量(本公司)
		int payedOrderCount = orderService.getMyQuoteOrderCount(currentRoleType, isAdmin, currentCompany, currentUser, OrderStateEnum.PAYED.getValue(), false);
		//已发货订单数量(本公司)
		int sendedOrderCount = orderService.getMyQuoteOrderCount(currentRoleType, isAdmin, currentCompany, currentUser, OrderStateEnum.SHIPED.getValue(), false);
        if(showChildCompanyTab) {
            //分公司订单数量
            int childCompanyOrderCount = orderService.getMyQuoteOrderCount(null, null, null, null, childCompanyList, null);
            model.addAttribute("childCompanyOrderCount", childCompanyOrderCount);
        }
		model.addAttribute("unPayOrderCount", unPayOrderCount);
		model.addAttribute("payedOrderCount", payedOrderCount);
		model.addAttribute("sendedOrderCount", sendedOrderCount);

		Map queryParam = CommonUtil.getParameterMap(request);
		queryParam.put("tab", tab);
		model.addAttribute("queryParam", queryParam);
        model.addAttribute("showChildCompanyTab", showChildCompanyTab);
		model.addAttribute("CommonUtil", FreemarkerUtils.getStaticModel(CommonUtil.class));
		model.addAttribute("adminOrfinance", adminOrfinance);
		model.addAttribute("onlyFinance", isFinance && !isAdmin);	//只是财务，不是管理员
		return "order/listQuoteOrder";
	}

    /**
     * 载入商品订单列表<br>
     * 采购商：管理员和财务，可以查看本公司以及分公司的所有订单，其他人只能查看自己的订单<br>
     * 供应商：都可以看本公司所有的订单
     * */
    @RequestMapping(value = "/product", method = RequestMethod.GET)
    public String listProductOrder(Model model) {
        int tab = getParaToInt("tab", 0);		//tab标签：0.全部订单 1.待付款  2.已付款  3.已发货  10.分公司订单
        int pageNo = getParaToInt("pageNo", 1);   //页码
        int pageSize = Globals.PAGESIZE;	//每页显示订单数
        String keyword = getParaTrim("keyword");	//关键字
        String sellerCompanyName = getParaTrim("sellerCompanyName");	//卖家名称
        String buyerCompanyName = getParaTrim("buyerCompanyName");	//买家名称
        Integer state = getParaToInt("state");	//订单状态（查询用）
        Date sdate = getParaToDate("sdate");	//开始日期
        Date edate = getParaToDate("edate");	//结束日期

        int currentRoleType = ContextUtil.getCurrentRoleType();
        User currentUser = ContextUtil.getUser();
        Company currentCompany = ContextUtil.getCompany();
        boolean isAdmin = ContextUtil.isAdmin();

		//构造查询参数
		Map param = new HashMap();
		param.put("keyword", keyword);
		param.put("sellerCompanyName", sellerCompanyName);
		param.put("buyerCompanyName", buyerCompanyName);
		param.put("state", state);
		param.put("sdate", sdate);
		if(edate != null) {
			param.put("edate", DateUtils.addDays(edate, 1));
		}

		boolean showChildCompanyTab = ContextUtil.isPurchaser() && isAdmin;	//是否显示分公司tab
		boolean adminOrfinance = isAdmin;		//是否是管理员或财务
		boolean onlyFinance = false;			//只是财务，不是管理员
		List<Company> childCompanyList = null;
		if(ContextUtil.isPurchaser()) {
			//采购商
			if(!isAdmin) {
				List<UserEnum> userenum = new ArrayList<>();
				userenum.add(UserEnum.cfinance);
				boolean isFinance = userService.getUserAuthorityByUserId(currentUser.getId(), userenum);	//是否是财务
				if(isFinance) {
					showChildCompanyTab = true;
					adminOrfinance = true;
					onlyFinance = !isAdmin;
				}
			}
			if(showChildCompanyTab) {
				childCompanyList = companyService.findAllChildCompany(currentCompany.getId());  //分公司
				if(CollectionUtil.isEmpty(childCompanyList)) {
					showChildCompanyTab = false;
				}
			}
			if(adminOrfinance) {
				if(tab != 10) {
					param.put("buyerCompanyId", ContextUtil.getCompanyId());
				} else {
					param.put("buyerCompanys", childCompanyList);
				}
			} else {
				param.put("buyerUserId", ContextUtil.getUserId());
			}
		} else {
			param.put("sellerCompanyId", ContextUtil.getCompanyId());
		}

        PageHelper.startPage(pageNo, pageSize);
        List<Map> orderList = orderService.searchProductOrder(param);

        for(Map order : orderList) {
			Integer orderId = Convert.toInt(order.get("id"));
			if(orderId != null) {
				List<OrderProduct> productList = orderService.findOrderProduct(orderId);
				order.put("productList", productList);
			}

			if(showChildCompanyTab && tab == 10) {
				//分公司获取总公司
				Integer buyerCompanyId = Convert.toInt(order.get("buyerCompanyId"));
				if(buyerCompanyId != null) {
					Company topCompany = companyService.getTopParentCompany(buyerCompanyId);
					if (topCompany != null) {
						order.put("topCompanyName", topCompany.getCompanyName());
					}
				}
			}

			List<OrderPayInfo> orderPay = orderPayService.findOrderPay(orderId, OrderPayResultEnum.SUBMIT.getValue(), OrderPayResultEnum.REVIEW.getValue(), OrderPayResultEnum.SUCCESS.getValue());
			order.put("paidSize", orderPay.size());
		}

        model.addAttribute("orderList", orderList);
        model.addAttribute("page", new PageInfo(orderList));
        model.addAttribute("orderStateMap", CommonUtil.getEnumMap(OrderStateEnum.class));   //交易状态
        //待付款订单数量(本公司)
        int unPayOrderCount = orderService.getMyProductOrderCount(currentRoleType, isAdmin, currentCompany, currentUser, OrderStateEnum.UNPAY.getValue(), false);
        //已付款订单数量(本公司)
        int payedOrderCount = orderService.getMyProductOrderCount(currentRoleType, isAdmin, currentCompany, currentUser, OrderStateEnum.PAYED.getValue(), false);
        //已发货订单数量(本公司)
        int sendedOrderCount = orderService.getMyProductOrderCount(currentRoleType, isAdmin, currentCompany, currentUser, OrderStateEnum.SHIPED.getValue(), false);
        if(showChildCompanyTab) {
            //分公司订单数量
            int childCompanyOrderCount = orderService.getMyProductOrderCount(null, null, null, childCompanyList, null);
            model.addAttribute("childCompanyOrderCount", childCompanyOrderCount);
        }
        model.addAttribute("unPayOrderCount", unPayOrderCount);
        model.addAttribute("payedOrderCount", payedOrderCount);
        model.addAttribute("sendedOrderCount", sendedOrderCount);

        Map queryParam = CommonUtil.getParameterMap(request);
        queryParam.put("tab", tab);
        model.addAttribute("queryParam", queryParam);
        model.addAttribute("showChildCompanyTab", showChildCompanyTab);
        model.addAttribute("CommonUtil", FreemarkerUtils.getStaticModel(CommonUtil.class));
		model.addAttribute("adminOrfinance", adminOrfinance);
		model.addAttribute("onlyFinance", onlyFinance);	//只是财务，不是管理员
        return "order/listProductOrder";
    }

	/**
	 * 载入订单详情页面
	 * */
	@RequestMapping("/{orderId}")
	public String viewOrder(@PathVariable Integer orderId, Model model) {
		OrderInfo order = orderService.getOrderInfoById(orderId);
		if(order != null) {
			if(order.getOrdertype().intValue() == OrderTypeEnum.ENQUIRY.getValue()) {
				//询价订单
				return "forward:/order/quote/" + orderId;
			} else {
				//商品订单
				return "forward:/order/product/" + orderId;
			}
		} else {
			throw new NoPermissionException();
		}
	}

	/**
	 * 载入询价订单详情页面
	 * */
	@RequestMapping("/quote/{orderId}")
	public String viewQuoteOrder(@PathVariable Integer orderId, Model model) {
		OrderInfoDto order = orderService.findById(orderId);
		if(!orderService.hasThisQuoteOrderPermission(ContextUtil.getUser(), ContextUtil.getCurrentRole(), order)) {
			throw new NoPermissionException();
		}
		Boolean isChildCompanyOrder = companyService.isChildCompany(ContextUtil.getCompany().getId(),order.getBuyerCompanyId());
		model.addAttribute("isChildCompanyOrder", isChildCompanyOrder);

		List<OrderDetailDto> orderDetail = orderService.findOrderDetailByOrderId(orderId);
		List<OrderShip> orderShip = orderService.findOrderShipByOrderId(orderId);
		List<OrderPayInfo> orderPay = orderPayService.findOrderPay(orderId, OrderPayResultEnum.SUBMIT.getValue(), OrderPayResultEnum.REVIEW.getValue(), OrderPayResultEnum.SUCCESS.getValue());
		model.addAttribute("isShipEnd", orderService.isShipEnd(orderId, null, null));
		model.addAttribute("unPayInfo", orderService.getUnPayInfo(orderId));
		model.addAttribute("orderInfo", order);
		model.addAttribute("orderDetails", orderDetail);
		model.addAttribute("orderShips",orderShip);
		model.addAttribute("orderPays",orderPay);
		model.addAttribute("orderStateMap", CommonUtil.getEnumMap(OrderStateEnum.class));
		model.addAttribute("topBuyerCompany", companyService.getTopParentCompany(order.getBuyerCompanyId()));
		model.addAttribute("address", orderService.getOrderAddress(orderId));
		model.addAttribute("onlyFinance", isOnlyFinance());
		model.addAttribute("isAdmin", ContextUtil.isAdmin());
//		PinganAccount baccount = pinganAccountService.getValidAccountByCompanyId(order.getBuyerCompanyId());
//		PinganAccount saccount = pinganAccountService.getValidAccountByCompanyId(order.getSellerCompanyId());
//		model.addAttribute("baccount", baccount);
//		model.addAttribute("saccount", saccount);

		return "order/viewOrder";
	}

	/**
	 * 载入商品订单详情页面
	 * */
	@RequestMapping("/product/{orderId}")
	public String viewProductOrder(@PathVariable Integer orderId, Model model) {
		OrderInfo order = orderService.getOrderInfoById(orderId);

		if(!orderService.hasThisProductOrderPermission(ContextUtil.getUser(), ContextUtil.getCurrentRole(), order)) {
			throw new NoPermissionException();
		}

		Company seller = companyService.getCompanyById(order.getSellerCompanyId());

		List<OrderProduct> productList = orderService.findOrderProduct(orderId);
		List<OrderShip> orderShip = orderService.findOrderShipByOrderId(orderId);
		List<OrderPayInfo> orderPay = orderPayService.findOrderPay(orderId, OrderPayResultEnum.SUBMIT.getValue(), OrderPayResultEnum.REVIEW.getValue(), OrderPayResultEnum.SUCCESS.getValue());
		model.addAttribute("isShipEnd", orderService.isShipEnd(orderId, null, null));
		model.addAttribute("unPayInfo", orderService.getUnPayInfo(orderId));
		model.addAttribute("order", order);
		model.addAttribute("seller", seller);
		model.addAttribute("productList", productList);
		model.addAttribute("orderShips",orderShip);
		model.addAttribute("orderPays",orderPay);
		model.addAttribute("orderStateMap", CommonUtil.getEnumMap(OrderStateEnum.class));
		model.addAttribute("topBuyerCompany", companyService.getTopParentCompany(order.getBuyerCompanyId()));
		model.addAttribute("address", orderService.getOrderAddress(orderId));
		model.addAttribute("onlyFinance", isOnlyFinance());
		model.addAttribute("isAdmin", ContextUtil.isAdmin());
//		PinganAccount baccount = pinganAccountService.getValidAccountByCompanyId(order.getBuyerCompanyId());
//		PinganAccount saccount = pinganAccountService.getValidAccountByCompanyId(order.getSellerCompanyId());
//		model.addAttribute("baccount", baccount);
//		model.addAttribute("saccount", saccount);
		return "order/viewProductOrder";
	}

	/**
	 * 取消订单
	 * */
	@ResponseBody
	@RequestMapping(value = "/cancelOrder")
	public AjaxJson cancelOrder() {
        Integer orderId = getParaToInt("orderId");
        String cancelReason = getPara("cancelReason");     //取消原因
        String cancelInstr = getPara("cancelInstr");       //补充说明

        if(orderId != null && StringUtils.isNotBlank(cancelReason)) {
			//todo 判断是否具有该订单权限
            orderService.cancelOrder(orderId, ContextUtil.getUserId(), ContextUtil.isPurchaser() ? 1 : 2, cancelReason, cancelInstr);
			return AjaxJson.success();
        }
		return AjaxJson.error("操作失败");
	}

	/**
     * 变更订单价格（只有在待付款状态才能变更价格）
     * */
	@ResponseBody
    @RequestMapping(value = "/modifyPrice")
	public AjaxJson modifyPrice() {
        Integer orderId = getParaToInt("orderId");
        Double price = getParaToDouble("price");

        if(orderId != null && price != null) {
            OrderInfo orderInfo = orderService.getOrderInfoById(orderId);
            if(orderInfo != null) {
                if(price < 0 || price > orderInfo.getOriginalPrice().doubleValue()) {
                    return AjaxJson.error("请输入正确的价格");
                }

                if(!orderService.hasThisOrderPermission(ContextUtil.getUser(), ContextUtil.getCurrentRole(), orderInfo)) {
                    return AjaxJson.error("您无权操作该订单");
                }
                //只有是待付款状态的订单才能变更价格
                if (orderInfo.getState().intValue() != OrderStateEnum.UNPAY.getValue()) {
                    return AjaxJson.error("该订单不能修改价格");
                }
                Double oldPrice = orderInfo.getTotalPrice();
                if(price.doubleValue() != oldPrice.doubleValue()) {
                    orderService.modifyOrderPrice(orderId, MathUtil.round(price, 2));

                    //发送通知信息
                    if (orderInfo.getOrdertype().intValue() == OrderTypeEnum.ENQUIRY.getValue()) {
                        //询价订单
                        EnqEnquiry enquiry = enquiryService.getEnquiryById(orderInfo.getEnquiryId());

                        Map<String, String> msgParam = new HashMap<>();
                        msgParam.put("enquiryName", enquiry.getEnquiryName());
                        msgParam.put("orderNumber", orderInfo.getOrderNumber());
                        msgParam.put("oldPrice", oldPrice.toString());
                        msgParam.put("newPrice", price.toString());
                        msgConfigService.sendMessage("MODIFY_PRICE", msgParam, null, orderInfo.getBuyerUserId());
                    } else {
                        //商品订单
                        orderService.sendProductOrderMsg("MODIFY_PRODUCT_ORDER", orderInfo, 1, Ret.create("oldPrice", oldPrice.toString()).set("newPrice", price));
                    }
                    return AjaxJson.success();
                } else {
                    return AjaxJson.error("金额未变更");
                }
            }

        }
        return AjaxJson.error("操作失败");
    }

	/**
	 * 未付款货物详情
	 * */
	@RequestMapping("/unpaid/{orderId}")
	public String unpaidDetail(@PathVariable Integer orderId, Model model) {
		OrderInfoDto orderInfoDto = orderService.findById(orderId);
		if(!orderService.hasThisQuoteOrderPermission(ContextUtil.getUser(), ContextUtil.getCurrentRole(), orderInfoDto)) {
			throw new NoPermissionException();
		}
		OrderInfo order = orderService.findById(orderId);
		List<OrderDetailDto> unpaidDetail = orderService.findUnpaidByOrderId(orderId);
		int companyId = order.getSellerCompanyId();
		Company company = companyService.getCompanyById(companyId);
		String companyName = company.getCompanyName();
		model.addAttribute("orderInfo", order);
		model.addAttribute("orderDetails", unpaidDetail);
		model.addAttribute("sellerName", companyName);
		return "order/unpaidProduct";
	}

	/**
	 * 已付款的货物详情
	 * */
	@RequestMapping("/shipDetail/{orderId}/{shipId}")
	public String shipDetail(@PathVariable Integer orderId,@PathVariable Integer shipId, Model model) {
		Integer index = getParaToInt("index");
		OrderInfoDto orderInfoDto = orderService.findById(orderId);
		if(!orderService.hasThisQuoteOrderPermission(ContextUtil.getUser(), ContextUtil.getCurrentRole(), orderInfoDto)) {
			throw new NoPermissionException();
		}
		OrderInfo order = orderService.findById(orderId);
		List<OrderShipProductDto> shipProduct = orderService.getShipProductDto(shipId);
		OrderShip orderShip = orderService.findOrderShipById(shipId);
		int companyId = order.getSellerCompanyId();
		Company company = companyService.getCompanyById(companyId);
		String companyName = company.getCompanyName();
		model.addAttribute("index", index);
		model.addAttribute("orderInfo", order);
		model.addAttribute("shipProducts", shipProduct);
		model.addAttribute("orderShip", orderShip);
		model.addAttribute("sellerName", companyName);
		return "order/shipDetail";
	}

	/**
	 * 获取快递信息
	 * */
	@ResponseBody
	@RequestMapping(value = "/kuaidi", method = RequestMethod.POST)
	public List<KuaidiDetail> getKuaidi (Integer shipId) {
		OrderShip ordership = orderService.findOrderShipById(shipId);
		int CompanyId = ordership.getDeliveryCompanyId();		//物流公司id
		String expressNumber = ordership.getExpressNumber();	//快递单号
		Delivery delivery = deliveryService.getDeliveryById(CompanyId);
		if(null!=delivery && delivery.getIfSupportApi()==1){
			String companyCode = delivery.getCompanyCode();		//物流公司代码
			KuaidiInfo kuaidi =  KuaidiUtil.getInfo(companyCode, expressNumber);
			List<KuaidiDetail> details = kuaidi.getDetails();
			return details;
		}
		return null;
	}

	/**
	 * 载入申请发货/主动发货/确认收货页面
	 * */
	@RequestMapping(value = "/ship/{orderId}", method = RequestMethod.GET)
	public String loadShip(@PathVariable Integer orderId, Model model) {
		//发货批次id
		//供应商（若shipId > 0，则显示指定的发货详情，若shipId=0，则显示主动发货页面，若为null，则显示最早的那批未发货的）
		//采购商（若shipId不为null，载入确认收货页面，为null则显示申请发货页面）
		Integer shipId = getParaToInt("shipId");

		OrderInfoDto orderInfo = orderService.findById(orderId);
		//订单权限判断
		if(!orderService.hasThisQuoteOrderPermission(ContextUtil.getUser(), ContextUtil.getCurrentRole(), orderInfo)) {
			throw new NoPermissionException();
		}

		//项目信息
		//EnqProject project = enquiryService.getEnqProjectById(orderInfo.getProjectId());
		//EnqEnquiry enquiry = enquiryService.getEnquiryById(orderInfo.getEnquiryId());
		//发货信息(已按批次排序)
		List<OrderShip> shipList = orderShipService.findOrderShip(orderId, null, null);
		//支付信息(已按批次排序)
		List<OrderPayInfo> payList = orderPayService.findOrderPay(orderId, OrderPayResultEnum.SUBMIT.getValue(), OrderPayResultEnum.REVIEW.getValue(), OrderPayResultEnum.SUCCESS.getValue());
		//收货信息(如果shipId不为null且shipId > 0，则读取ship表的收货地址，否则读取订单中的)
		if(shipId != null && shipId > 0) {
			model.addAttribute("address", orderShipService.getShipAddress(shipId));
		} else {
			model.addAttribute("address", orderService.getOrderAddress(orderId));
		}

		//发货清单
		List<Map> detailList = new ArrayList<>();
		if(ContextUtil.isPurchaser()) {
			//当前是采购商身份
			if(shipId == null) {
				//载入申请发货页面
				List<OrderDetailDto> detailDtoList = orderService.findOrderDetailByOrderId(orderId);
				detailList = BeanUtils.copyListMap2ListBean(detailDtoList);
			} else {
				//载入确认收货页面
				List<OrderShipProductDto> shipProductList = orderShipProductMapper.findOrderShipProduct(null, shipId, null);
				detailList = BeanUtils.copyListMap2ListBean(shipProductList);
			}
		} else {
			//当前是供应商身份，载入主动发货页面（三种情况：载入最早那批未发货、指定批次、主动发货页面）
			if(shipId == null) {
				//显示最早那批未发货的页面，如没有，则显示主动发货页面
				//获取最早的未发货的信息
				OrderShip ship = orderShipService.getFstUnShip(orderId);
				if(ship != null) {
					shipId = ship.getId();
				} else {
					//没有未发货的产品，显示主动发货页面
					shipId = 0;
				}

			}
			if(shipId == 0) {
				//显示主动发货页面
				List<OrderDetailDto> detailDtoList = orderService.findOrderDetailByOrderId(orderId);
				detailList = BeanUtils.copyListMap2ListBean(detailDtoList);
			} else if(shipId > 0) {
				//显示指定的批次
				List<OrderShipProductDto> shipProductList = orderShipProductMapper.findOrderShipProduct(null, shipId, null);
				detailList = BeanUtils.copyListMap2ListBean(shipProductList);
			}

			//是否已经发完货
			boolean isShipEnd = orderService.isShipEnd(orderId, null, null);
			model.addAttribute("isShipEnd", isShipEnd);

			//获取快递公司
			List<Delivery> deliveryList = deliveryService.findAllDelivery();
			model.addAttribute("deliveryList", deliveryList);
		}

		if(shipId != null && shipId > 0) {
			//当前显示的ship信息
			OrderShip ship = orderShipService.getOrderShipById(shipId);
			model.addAttribute("ship", ship);
		}

		//model.addAttribute("project", project);
		//model.addAttribute("enquiry", enquiry);
		model.addAttribute("order", orderInfo);
		model.addAttribute("payList", payList);
		model.addAttribute("shipList", shipList);
		model.addAttribute("detailList", detailList);
		model.addAttribute("PayMode", CommonUtil.getEnumMap(OrderPayModeEnum.class));
		model.addAttribute("CommonUtil", FreemarkerUtils.getStaticModel(CommonUtil.class));
		model.addAttribute("showShipId", shipId);		//当前显示的是哪个shipId的信息，申请发货则为null，供应商显示主动发货的时候为0
		return "order/ship";
	}

	/**
	 * 载入商品发货、收货页面
	 * */
	@RequestMapping(value = "/ship/product/{orderId}", method = RequestMethod.GET)
	public String loadProductShip(@PathVariable Integer orderId, Model model) {
		OrderInfo order = orderService.getOrderInfoById(orderId);

        if(!orderService.hasThisProductOrderPermission(ContextUtil.getUser(), ContextUtil.getCurrentRole(), order)) {
            throw new NoPermissionException();
        }

        if(ContextUtil.isPurchaser()) {
            //确认收货页面
            if(order.getState().intValue() != OrderStateEnum.SHIPED.getValue()) {
                return "redirect:/order/" + orderId;
            }

            //发货信息(已按批次排序)
            List<OrderShip> shipList = orderShipService.findOrderShip(orderId, null, null);
            //收货信息（读取发货表里面的）
            model.addAttribute("address", orderShipService.getShipAddress(shipList.get(0).getId()));
            model.addAttribute("shipList", shipList);
        } else if(ContextUtil.isProvider()) {
            //发货页面
            if(order.getState().intValue() != OrderStateEnum.UNPAY.getValue() && order.getState().intValue() != OrderStateEnum.PAYED.getValue()) {
                return "redirect:/order/" + orderId;
            }
            //收货信息（读取订单表里面的）
            model.addAttribute("address", orderService.getOrderAddress(orderId));
            //获取快递公司
            List<Delivery> deliveryList = deliveryService.findAllDelivery();
            model.addAttribute("deliveryList", deliveryList);
        }

        Company seller = companyService.getCompanyById(order.getSellerCompanyId());
        List<OrderProduct> productList = orderService.findOrderProduct(orderId);        //商品列表


		//支付信息(已按批次排序)
		List<OrderPayInfo> payList = orderPayService.findOrderPay(orderId, OrderPayResultEnum.SUBMIT.getValue(), OrderPayResultEnum.REVIEW.getValue(), OrderPayResultEnum.SUCCESS.getValue());

		model.addAttribute("order", order);
        model.addAttribute("seller", seller);
		model.addAttribute("payList", payList);
		model.addAttribute("productList", productList);
		model.addAttribute("PayMode", CommonUtil.getEnumMap(OrderPayModeEnum.class));
		model.addAttribute("CommonUtil", FreemarkerUtils.getStaticModel(CommonUtil.class));
		return "order/shipProduct";
	}

	/**
	 * 判断是否支持api,获取快递单号和物流公司代码
	 * */
	@ResponseBody
	@RequestMapping(value = "/ifApi", method = RequestMethod.POST)
	public KuaidiDelivery ifApi (Integer shipId) {

		KuaidiDelivery kuaidi = new KuaidiDelivery();
		OrderShip ordership = orderService.findOrderShipById(shipId);
		int CompanyId = ordership.getDeliveryCompanyId();		//物流公司id
		String expressNumber = ordership.getExpressNumber();	//快递单号
		Delivery delivery = deliveryService.getDeliveryById(CompanyId);
		String companyCode = delivery.getCompanyCode();	        //物流公司代码
		int ifApi = delivery.getIfSupportApi();
		kuaidi.setExpressNumber(expressNumber);
		kuaidi.setCompanyCode(companyCode);
		kuaidi.setIfSupportApi(ifApi);
		return kuaidi;

	}
    /**
	 * 申请发货/主动发货/确认收货
	 * 1. 当前用户是采购商：shipId不为null，为确认收货，否则为申请发货
	 * 2. 当前用户是供应商：shipId不为null，为处理买家的发货申请，否则为主动发货
	 * */
	@ResponseBody
	@RequestMapping(value = "/ship", method = RequestMethod.POST)
	public AjaxJson ship(ShipData shipData) {
		String code = getPara("code");		//验证码
		if(shipData != null) {
			try {
				int type = ShipRequestTypeEnum.getType(ContextUtil.getCurrentRole().getRoleType(), shipData.getShipId());
				if(type == ShipRequestTypeEnum.SIGN.getValue()) {
					//确认收货，需要验证验证码
					VerifyCode verifyCode = (VerifyCode)request.getSession().getAttribute(Globals.SIGN_SHIP_CODE);
					if(verifyCode == null || !StringUtils.equalsIgnoreCase(verifyCode.getCode(), code.toString()) || verifyCode.getExpireTime().before(new Date())) {
						return AjaxJson.error("验证码不正确");
					}
				}

				OrderShip ship = orderService.ship(shipData, ContextUtil.getUser(), ContextUtil.getCurrentRole());
				AjaxJson aj = AjaxJson.success();
				aj.setObj(ship.getId());
				return aj;
			} catch (BaseException be) {
				return AjaxJson.error(be.getErrorCode());
			}
		}
		return AjaxJson.error("操作失败");
	}

	/**
     * 商品订单发货
     * */
    @ResponseBody
    @RequestMapping(value = "/product/ship", method = RequestMethod.POST)
    public AjaxJson shipProductOrder(ShipData shipData) {
        if(shipData == null) {
            return AjaxJson.error();
        }
        try {
            orderService.shipProductOrder(shipData, ContextUtil.getUser(), ContextUtil.getCurrentRole());
            return AjaxJson.success();
        } catch (BaseException be) {
            return AjaxJson.error(be.getErrorCode());
        }
    }

    /**
     * 商品订单确认收货
     * */
    @ResponseBody
    @RequestMapping(value = "/product/sign", method = RequestMethod.POST)
    public AjaxJson signProductOrder() {
        Integer orderId = getParaToInt("orderId");
        String code = getParaTrim("code");		//验证码
        if(orderId == null) {
            return AjaxJson.error();
        }
        if(StrUtil.isBlank(code)) {
            return AjaxJson.error("请输入验证码");
        }
        //确认收货，需要验证验证码
        VerifyCode verifyCode = (VerifyCode)request.getSession().getAttribute(Globals.SIGN_SHIP_CODE);
        if(verifyCode == null || !StringUtils.equalsIgnoreCase(verifyCode.getCode(), code.toString()) || verifyCode.getExpireTime().before(new Date())) {
            return AjaxJson.error("验证码不正确");
        }
        try {
            orderService.signProductOrder(orderId, ContextUtil.getUser(), ContextUtil.getCurrentRole());
            return AjaxJson.success();
        } catch (BaseException e) {
            return AjaxJson.error(e.getErrorCode());
        }
    }

	/**
	 * 发送确认收货验证码
	 * */
	@ResponseBody
	@RequestMapping(value = "/signCode", method = RequestMethod.POST)
	public AjaxJson sendSignShipCode() {
		Integer orderId = getParaToInt("orderId");
		Integer shipId = getParaToInt("shipId");
		if(orderId == null) {
			return AjaxJson.error();
		}
		//询价订单确认收货的时候需要传shipId，商品订单不需要
		if(shipId != null) {
			//判断是否可以确认收货，如果已付完全部款项，则均可确认收货，否则付款金额需大于之前确认收货的货物金额 + 本次确认收货的金额
			String msg = orderService.checkSignQuoteOrder(orderId, shipId);
			if (StrUtil.isNotBlank(msg)) {
				return AjaxJson.error(msg);
			}
		} else {
			String msg = orderService.checkSignProductOrder(orderId);
			if(StrUtil.isNotBlank(msg)) {
				return AjaxJson.error(msg);
			}
		}
		User user = ContextUtil.getUser();
		String code = RandomStringUtils.randomNumeric(6);
		LOGGER.info("signShip sms code:" + code);
		VerifyCode verifyCode = new VerifyCode(code, new Date(), DateUtils.addMinutes(new Date(), 15));
		request.getSession().setAttribute(Globals.SIGN_SHIP_CODE, verifyCode);

		Map<String, String> msgParam = new HashMap<>();
		msgParam.put("code", code);
		msgParam.put("time", "15");
		msgConfigService.sendMessageWithOutUserId("SIGN_CODE", msgParam, user.getMobile(), StrUtil.isNotBlank(user.getMobile()) ? null : user.getEmail(), false);
		return AjaxJson.success();
	}

	/**
	 * 订单列表页面显示公司信息tip
	 * */
	@ResponseBody
	@RequestMapping(value = "/loadCompanyTip", method = RequestMethod.POST)
	public AjaxJson loadCompanyTip() {
		Integer companyId = getParaToInt("companyId");
		Integer userId = getParaToInt("userId");
		String type = getParaTrim("type");		//type为product时为商品订单
		if(companyId != null) {
			Ret ret = Ret.create();
			Map companyInfo = companyService.getOrderCompanyTip(companyId);
			if(companyInfo != null) {
				ret.set(companyInfo).put("orderId", getParaToInt("orderId"));
			}
			if(userId == null && "product".equals(type)) {
				CompanyExt companyExt = companyService.getCompanyExtByCustomerid(companyId);
				if(companyExt != null) {
					ret.set("userName", companyExt.getCantactName()).set("contact", companyExt.getCantactTel());
				}
			} else if(userId != null) {
				User user = userService.getUserById(userId);
				if(user != null) {
					ret.set("userName", user.getRealName()).set("contact", StringUtils.isNotBlank(user.getMobile()) ? user.getMobile() : user.getEmail());
				}
			}
			if(!ret.isEmpty()) {
				return AjaxJson.success().setObj(ret);
			}
		}
		return AjaxJson.error("获取信息失败");
	}

	/**
	 * 订单列表页面显示收货人信息tip
	 * */
	@ResponseBody
	@RequestMapping(value = "/loadPeoTip", method = RequestMethod.POST)
	public AjaxJson loadPeoTip() {
		Integer orderId = getParaToInt("orderId");
		if(orderId != null) {
			Map address = orderService.getOrderAddress(orderId);
			if(address != null) {
				AjaxJson aj = AjaxJson.success();
				aj.setObj(address);
				return aj;
			}
		}
		return AjaxJson.error("获取信息失败");
	}

	@Autowired
	private PinganPayMapper pinganPayMapper;
	/**
	 * 订单列表页面显示分批支付详情
	 * */
	@ResponseBody
	@RequestMapping(value = "/loadBatchPayTip", method = RequestMethod.POST)
	public AjaxJson loadBatchPayTip() {
		Integer orderId = getParaToInt("orderId");
		if(orderId != null) {
			OrderInfo orderInfo = orderService.getOrderInfoById(orderId);
			if(orderInfo != null) {
				Map map = new HashMap();
				List<Map> list = new ArrayList<>();
				List<OrderPayInfo> payList = orderPayService.findOrderPay(orderId, OrderPayResultEnum.SUBMIT.getValue(), OrderPayResultEnum.REVIEW.getValue(), OrderPayResultEnum.SUCCESS.getValue());
				OrderPayInfo unPayInfo = orderService.getUnPayInfo(orderId);		//待支付记录
				for (OrderPayInfo orderPay : payList) {
					double payPrice = orderPay.getTotalPrice();        //支付金额
					Date payTime = orderPay.getPayTime();        //支付时间

					Map m = new HashMap();
					m.put("payPrice", payPrice);
					m.put("payTime", payTime == null ? "" : CommonUtil.formatDate(payTime, "yyyy-MM-dd"));
					m.put("payResult", orderPay.getPayResult());
					int ppState = 0;
					if (orderPay.getPayMode().compareTo(OrderPayModeEnum.PINGAN.getValue()) == 0) {//平安支付的话
						Example exp = new Example(PinganPay.class);
						exp.createCriteria().andEqualTo("thirdHtId", orderPay.getPayNumber());
						List<PinganPay> pinganPays = pinganPayMapper.selectByExample(exp);
						if (pinganPays.size() > 0) {
							ppState = pinganPays.get(0).getState();
						}
					}
					m.put("ppState", ppState);
					list.add(m);

				}
				map.put("list", list);

				if(unPayInfo != null && unPayInfo.getTotalPrice() > 0) {
					//订单未全部支付完
					map.put("unPayPrice", unPayInfo.getTotalPrice());	//未支付的金额
				}
				AjaxJson aj = AjaxJson.success();
				aj.setObj(map);
				return aj;
			}
		}
		return AjaxJson.error("获取信息失败");
	}

	/**
	 * 订单列表页面显示分批发货详情
	 * */
	@ResponseBody
	@RequestMapping(value = "/loadBatchShipTip", method = RequestMethod.POST)
	public AjaxJson loadBatchShipTip() {
        Integer orderId = getParaToInt("orderId");
        if(orderId != null) {
            OrderInfo orderInfo = orderService.getOrderInfoById(orderId);
            if(orderInfo != null) {
                Map map = new HashMap();
                List<Map> list = new ArrayList<>();
                List<OrderShip> shipList = orderShipService.findOrderShip(orderId, null, null);    //获取发货记录
                double totalShipPrice = 0d;
                for (OrderShip orderShip : shipList) {
                    Integer ifApply = orderShip.getIfApply();       //是否是申请发货
                    Integer shipState = orderShip.getShipState();       //发货状态
                    Double totalPrice = orderShip.getTotalPrice();      //货款总额
                    Date shipTime = orderShip.getShipTime();        //发货时间

                    Map m = new HashMap();
                    if(ifApply == 1) {
                        m.put("applyPrice", totalPrice);    //请货金额
                    }
                    if(shipState != ShipStateEnum.UNSHIP.getValue()) {
                        m.put("shipPrice", totalPrice);     //发货金额
                        m.put("shipTime", shipTime == null ? "" : CommonUtil.formatDate(shipTime, "yyyy-MM-dd"));   //发货时间
                    }
                    list.add(m);

                    totalShipPrice = MathUtil.add(totalShipPrice, totalPrice);
                }

                map.put("list", list);
                if(!orderService.isShipEnd(orderId, null, null)) {
                    //货物未全部发完
                    map.put("unShipPrice", MathUtil.subtract(orderInfo.getOriginalPrice(), totalShipPrice));	//未发货的货款
                }
                return AjaxJson.success().setObj(map);
            }
        }
        return AjaxJson.error("获取信息失败");
	}

	/**
	 * 载入支付页面
	 * */
	@RequestMapping(value = "/pay_{onOff}/{orderId}/{payId}", method = RequestMethod.GET)
	public String loadPay( @PathVariable String onOff ,@PathVariable Integer orderId, @PathVariable Integer payId, Model model) {
		OrderInfo orderInfo = orderService.getOrderInfoById(orderId);
		if(!orderService.hasThisOrderPermission(ContextUtil.getUser(), ContextUtil.getCurrentRole(), orderInfo)) {
			throw new NoPermissionException();
		}

		OrderPayInfo payInfo = orderPayService.getOrderPayInfoById(payId);

		String province = dictionaryService.findByCodes(orderInfo.getReceiptProvince());
		String city = dictionaryService.findByCodes(orderInfo.getReceiptCity());
		String area = dictionaryService.findByCodes(orderInfo.getReceiptArea());

		if(orderInfo.getOrdertype().intValue() == OrderTypeEnum.ENQUIRY.getValue()) {
			//询价订单
			EnqEnquiry enquiry = enquiryService.getEnquiryById(orderInfo.getEnquiryId().intValue());
			EnqProject project = enquiryService.getEnqProjectById(enquiry.getProjectId());
			model.addAttribute("enquiry", enquiry);
			model.addAttribute("project", project);
		} else {
			//商城订单
			String title = "";
			List<OrderProduct> productList = orderService.findOrderProduct(orderInfo.getId());
			if (CollectionUtil.isNotEmpty(productList)) {
				if (productList.size() == 1) {
					title = productList.get(0).getProductName();
				} else {
					title = "\"" + productList.get(0).getProductName() + "\"等" + productList.size() + "件";
				}
			}
			model.addAttribute("title", title);
		}

		model.addAttribute("order", orderInfo);
		model.addAttribute("province", province);
		model.addAttribute("city", city);
		model.addAttribute("area", area);
		model.addAttribute("payInfo", payInfo);
//		model.addAttribute("successPayList", successPayList);
		//model.addAttribute("cateCount", orderService.getOrderDetailCateCount(orderId));
		model.addAttribute("CommonUtil", FreemarkerUtils.getStaticModel(CommonUtil.class));
//		IntegralRule integralRule = null;
		if ("off".equals(onOff)) {//线下支付
			IntegralRule integralRulePz = integralService.getIngralRuleByCode("offline_payment_ticket");
			IntegralRule integralRuleHt = integralService.getIngralRuleByCode("offline_payment_contract");
            model.addAttribute("integralRulePz", integralRulePz);
            model.addAttribute("integralRuleHt", integralRuleHt);
            return "pingan/payOffline";
        }else if ("on".equals(onOff)) {//线上支付
            PinganAccount buyer = pinganAccountService.getValidAccountByCompanyId(orderInfo.getBuyerCompanyId());
            PinganAccount seller = pinganAccountService.getValidAccountByCompanyId(orderInfo.getSellerCompanyId());

            Company sellCompany = companyService.getCompanyById(orderInfo.getSellerCompanyId());
            int useCoin = 0;
            if (sellCompany.getIfSelf().compareTo(1) == 0) {//为自营商城
                useCoin = coinService.getCoinByCompanyId(orderInfo.getBuyerCompanyId());//可用安装币
            }
            IntegralRule integralRule = integralService.getIngralRuleByCode("online_payment");
            UserAccount userAccount = userService.getUserAccountByUserId(ContextUtil.getUserId());
            double hasIntegral = userAccount == null ? 0d : userAccount.getUsIntegral().doubleValue();
			Integer minIng = giftService.getMinIntegralAmount();
			double mi = minIng.doubleValue();
			double ns = integralRule.getScore();
			double needDan = 0;
			if ((hasIntegral + ns) < mi) {//需要继续下单
				needDan = Math.ceil((minIng - hasIntegral - ns) / ns);
			}


			model.addAttribute("useCoin", useCoin);
			model.addAttribute("buyer", buyer);
			model.addAttribute("seller", seller);
			model.addAttribute("needDan", needDan);
			model.addAttribute("ns", ns);
			try {
				model.addAttribute("companyCode", DESUtils.encryptCompanyId(orderInfo.getBuyerCompanyId()));
			} catch (Exception e) {
				e.printStackTrace();
			}
			return "pingan/payOnline";
		}
		return "pingan/payOffline";
//		return "order/pay";
	}

	@RequestMapping( value = "/getCanUseCoins")
	@ResponseBody
	public AjaxJson getCanUseCoins(double amount , String orderType) {//orderType: 1 商城订单  2 项目订单  两种抵扣比例不同的
		int coins = coinService.getCanHandleCoin(amount, CoinRule.PAY_MALL_DUC, ContextUtil.getCompanyId());
		int addoins = coinService.getCanHandleCoin(amount, "1".equals(orderType)? CoinRule.PAY_MALL_ADD : CoinRule.PAY_ENQ_ADD, ContextUtil.getCompanyId());
		AjaxJson json = new AjaxJson();
		Map<String, Object> att = new HashMap<String, Object>();
		att.put("coins", coins);
		att.put("addCoins", addoins);
		json.setAttributes(att);
		return json;
	}

	/**
	 * 载入支付页面
	 * */
	@RequestMapping(value = "/pay2/{orderId}/{payId}", method = RequestMethod.GET)
	public String loadPay2(@PathVariable Integer orderId, @PathVariable Integer payId, Model model) {
		OrderInfoDto orderInfoDto = orderService.findById(orderId);
		if(!orderService.hasThisQuoteOrderPermission(ContextUtil.getUser(), ContextUtil.getCurrentRole(), orderInfoDto)) {
			throw new NoPermissionException();
		}
		//获取买卖双方的付款账户信息
		//CompanyBank buyerCompanyBank = companyService.getCompanyPayBank(orderInfoDto.getBuyerCompanyId());
		CompanyBank buyerCompanyBank = companyService.getCompanyPayBank(ContextUtil.getCompanyId());

		CompanyBank sellerCompanyBank = companyService.getCompanyPayBank(orderInfoDto.getSellerCompanyId());

		OrderPayInfo payInfo = orderPayService.getOrderPayInfoById(payId);
		List<OrderPayInfo> successPayList = orderPayService.findOrderPay(orderId, OrderPayResultEnum.SUCCESS.getValue());

		String province = dictionaryService.findByCodes(orderInfoDto.getReceiptProvince());
		String city = dictionaryService.findByCodes(orderInfoDto.getReceiptCity());
		String area = dictionaryService.findByCodes(orderInfoDto.getReceiptArea());

		model.addAttribute("order", orderInfoDto);
		model.addAttribute("province", province);
		model.addAttribute("city", city);
		model.addAttribute("area", area);
		model.addAttribute("buyerCompanyBank", buyerCompanyBank);
		model.addAttribute("sellerCompanyBank", sellerCompanyBank);
		model.addAttribute("payInfo", payInfo);
		model.addAttribute("successPayList", successPayList);
		//model.addAttribute("cateCount", orderService.getOrderDetailCateCount(orderId));
		model.addAttribute("CommonUtil", FreemarkerUtils.getStaticModel(CommonUtil.class));
//		return "pingan/payOffline";
		return "order/pay";
	}

	/**
	 * 询价订单财务管理列表页
	 */
	@RequestMapping("/payList")
	public String quotePayList(Model model) {
		int pageNo = getParaToInt("pageNo", 1); // 页码
		int pageSize = Globals.PAGESIZE; // 每页显示支付数
		String keyword = getPara("keyword"); // 关键字
		String sellerName = getPara("sellerName"); // 卖家名称
		String buyerName = getPara("buyerName"); // 买家名称
		String buyerId = getPara("buyerId");
		Integer payResult = getParaToInt("payResult"); // 支付状态（查询用）
		Date sdate = getParaToDate("sdate");	//开始日期
		Date edate = getParaToDate("edate");	//结束日期

		// 构造查询参数
		Map param = new HashMap();
		param.put("keyword", keyword);
		param.put("sellerName", sellerName);
		param.put("buyerName", buyerName);
		param.put("payResult", payResult);
		param.put("sdate", sdate);
		if (edate != null) {
			param.put("edate", DateUtils.addDays(edate, 1));
		}

		List<Company> childCompanyList = null;
		if (ContextUtil.isPurchaser()) {
			// 采购商
			childCompanyList = companyService.findAllChildCompany(ContextUtil.getCompany().getId()); // 分公司
			model.addAttribute("childCompanyList", childCompanyList);
			if (null!=buyerId && ""!= buyerId)
			{
				param.put("buyerCompanyId", buyerId);
			}else{
				param.put("buyerCompanyId", ContextUtil.getCompany().getId());// 总公司订单支付
				param.put("buyerCompanys", childCompanyList);// 总公司订单支付
			}
		} else if (ContextUtil.isProvider()) {
			param.put("sellerCompanyId", ContextUtil.getCompany().getId());
		}

		PageHelper.startPage(pageNo, pageSize);
		List<Map> orderPayList = orderService.searchOrderPayGroupByOrderid(param);

		if (ContextUtil.isPurchaser()) {
			model.addAttribute("companyId", ContextUtil.getCompany().getId());
			for (int i = 0; i < orderPayList.size(); i++) {
				Map m = orderPayList.get(i);
				boolean isFenBuy = false;
				for (int j = 0; j < childCompanyList.size(); j++) {
					Company company = childCompanyList.get(j);
					if (company.getId() == (Integer) m.get("buyerCompanyId")) {
						isFenBuy = true;
					}
				}
				m.put("isFenBuy", isFenBuy);
			}
		}else{
			for (int i = 0; i < orderPayList.size(); i++) {
				Map m = orderPayList.get(i);
				boolean isChild = false;
				int buyerCompanyId = (Integer)m.get("buyerCompanyId");
				Company company = companyService.getCompanyById(buyerCompanyId);
				Integer parentId = company.getParentId();
				if(null != parentId){
					String parentName = companyService.getTopParentCompany(buyerCompanyId).getCompanyName();
					isChild = true;
					m.put("parentName", parentName);
				}
				m.put("isChild", isChild);
			}
		}
		model.addAttribute("orderPayList", orderPayList);
		model.addAttribute("page", new PageInfo(orderPayList));
		//model.addAttribute("OrderPayResultMap", CommonUtil.getEnumMap(OrderPayResultEnum.class)); // 交易状态

		Integer buyerCompanyId = Convert.toInt(param.get("buyerCompanyId"));
		Integer sellerCompanyId = Convert.toInt(param.get("sellerCompanyId"));
		int failCount;
		int initCount;
		int submitCount;
		if (ContextUtil.isPurchaser()) {
			// 失败数量
			failCount = orderService.getMyOrderPayGroupByOrderidCount(ContextUtil.getCompany().getId(),null, childCompanyList, OrderPayResultEnum.FAIL.getValue());
			// 待支付数量
			initCount = orderService.getMyOrderPayGroupByOrderidCount(ContextUtil.getCompany().getId(), null, childCompanyList, OrderPayResultEnum.INIT.getValue());
			// 待审核数量+成功数量
			submitCount = orderService.getMyOrderPayGroupByOrderidCount(ContextUtil.getCompany().getId(), null, childCompanyList, OrderPayResultEnum.SUBMIT.getValue());
			
			if(!buyerCompanyId.equals(ContextUtil.getCompany().getId())){
				if(null!=payResult && 0==payResult){
					failCount = orderService.getMyOrderPayGroupByOrderidCount(buyerCompanyId,null, null,OrderPayResultEnum.FAIL.getValue());
				}
				if(null!=payResult && -1==payResult){
					initCount = orderService.getMyOrderPayGroupByOrderidCount(buyerCompanyId,null, null,OrderPayResultEnum.INIT.getValue());
				}
				if(null!=payResult && 1==payResult){
					submitCount = orderService.getMyOrderPayGroupByOrderidCount(buyerCompanyId,null, null,OrderPayResultEnum.SUBMIT.getValue());
				}
			}
		}else{
			failCount = orderService.getMyOrderPayGroupByOrderidCount(null, sellerCompanyId, null,
					OrderPayResultEnum.FAIL.getValue());
			initCount = orderService.getMyOrderPayGroupByOrderidCount(null, sellerCompanyId, null,
					OrderPayResultEnum.INIT.getValue());
			submitCount = orderService.getMyOrderPayGroupByOrderidCount(null, sellerCompanyId, null,
					OrderPayResultEnum.SUBMIT.getValue());
		}
		model.addAttribute("failCount", failCount);
		model.addAttribute("initCount", initCount);
		model.addAttribute("submitCount", submitCount);

		Map queryParam = CommonUtil.getParameterMap(request);
		if (payResult == null) {
			queryParam.put("payResult", "-1");
		}
		model.addAttribute("queryParam", queryParam);
		model.addAttribute("CommonUtil", FreemarkerUtils.getStaticModel(CommonUtil.class));
		return "order/payList";
	}

	/**
	 * 商品订单财务管理列表页
	 */
	@RequestMapping("/pay/product")
	public String listProductPay(Model model) {
        int pageNo = getParaToInt("pageNo", 1);
        int pageSize = Globals.PAGESIZE;
        int tab = getParaToInt("tab", 1);       //1.待支付  2.已支付  3.支付失败
        String keyword = getParaTrim("keyword");
        Integer buyerCompanyId = getParaToInt("buyerCompanyId");
        String sellerCompanyName = getParaTrim("sellerCompanyName");
        String buyerCompanyName = getParaTrim("buyerCompanyName");
        Date sdate = getParaToDate("sdate");
        Date edate = getParaToDate("edate");

        String payResult = "";
        if(tab == 1) {
            //待付款
            payResult = "-1";
        } else if(tab == 2) {
            //已支付
            payResult = "1,2,3";
        } else if(tab == 3) {
            //支付失败
            payResult = "0";
        }

		// 构造查询参数
		Map param = new HashMap();
		param.put("payResult", payResult);
        param.put("keyword", keyword);
        param.put("sellerCompanyName", sellerCompanyName);
		param.put("buyerCompanyName", buyerCompanyName);
        param.put("buyerCompanyId", buyerCompanyId);
		param.put("sdate", sdate);
		if (edate != null) {
			param.put("edate", DateUtils.addDays(edate, 1));
		}

		List<Company> childCompanyWithSelf = new ArrayList<>();     //本公司以及所有子公司
		if(ContextUtil.isPurchaser()) {
            //采购商
			//查询本公司及所有子公司的支付记录
			childCompanyWithSelf.add(ContextUtil.getCompany());
			childCompanyWithSelf.addAll(companyService.findAllChildCompany(ContextUtil.getCompanyId()));
			if(buyerCompanyId == null) {
				param.put("buyerCompanys", childCompanyWithSelf);
			}
        } else {
            //供应商
            param.put("sellerCompanyId", ContextUtil.getCompanyId());
        }

		PageHelper.startPage(pageNo, pageSize);
		List<Map> list = orderPayService.searchProductPay(param);

        for(Map orderPay : list) {
            //获取商品
            Integer orderId = Convert.toInt(orderPay.get("orderId"));
            List<OrderProduct> productList = orderService.findOrderProduct(orderId);
            orderPay.put("productList", productList);

			Integer buyerParentCompanyId = Convert.toInt(orderPay.get("buyerParentCompanyId"));
			if(buyerParentCompanyId != null) {
				//分公司下的单，获取总公司名称
				Company topCompany = companyService.getTopParentCompany(Convert.toInt(orderPay.get("buyerCompanyId")));
				orderPay.put("topCompany", topCompany);
			}
        }

        Integer _sellerCompanyId = Convert.toInt(param.get("sellerCompanyId"));
        int unPayedCount = orderPayService.getProductPayCount(buyerCompanyId, _sellerCompanyId, childCompanyWithSelf, "-1");    //待支付数量
        int payedCount = orderPayService.getProductPayCount(buyerCompanyId, _sellerCompanyId, childCompanyWithSelf, "1,2,3");    //已支付数量
        if(ContextUtil.isPurchaser()) {
            int failCount = orderPayService.getProductPayCount(buyerCompanyId, _sellerCompanyId, childCompanyWithSelf, "0");    //支付失败数量
            model.addAttribute("failCount", failCount);
        }
        Map queryParam = WebUtils.getParametersStartingWith(request, null);
        queryParam.put("tab", tab);

        model.addAttribute("queryParam", queryParam);
        model.addAttribute("list", list);
        model.addAttribute("page", new PageInfo(list));
        model.addAttribute("unPayedCount", unPayedCount);
		model.addAttribute("payedCount", payedCount);
        model.addAttribute("childCompanyWithSelf", childCompanyWithSelf);
		return "order/listProductPay";
	}

	/**
	 * 财务管理详情
	 */
	@RequestMapping("/payDetail/{orderId}")
	public String payDetail(@PathVariable Integer orderId, Model model) {
		OrderInfo order = orderService.findById(orderId);
		if(!orderService.hasThisOrderPermission(ContextUtil.getUser(), ContextUtil.getCurrentRole(), order)) {
			throw new NoPermissionException();
		}
		List<OrderPayInfo> orderPay = orderPayService.findOrderPay(orderId, OrderPayResultEnum.SUBMIT.getValue(), OrderPayResultEnum.REVIEW.getValue(), OrderPayResultEnum.SUCCESS.getValue());
		//CompanyBank buyerCompanyBank = companyService.getCompanyPayBank(order.getBuyerCompanyId());
		//CompanyBank sellerCompanyBank = companyService.getCompanyPayBank(order.getSellerCompanyId());

		model.addAttribute("orderInfo", order);
		model.addAttribute("orderPays", orderPay);
		//model.addAttribute("buyerCompanyBank", buyerCompanyBank);
		//model.addAttribute("sellerCompanyBank", sellerCompanyBank);
		//model.addAttribute("cateCount", orderService.getOrderDetailCateCount(orderId));
		PinganAccount baccount = pinganAccountService.getValidAccountByCompanyId(order.getBuyerCompanyId());
		PinganAccount saccount = pinganAccountService.getValidAccountByCompanyId(order.getSellerCompanyId());
		model.addAttribute("baccount", baccount);
		model.addAttribute("saccount", saccount);

		model.addAttribute("topBuyerCompany", companyService.getTopParentCompany(order.getBuyerCompanyId()));
		return "order/payDetail";
	}

	/**
	 * 显示询价订单和商品订单中支付过的付款记录（包括待审核和待复核）
	 * */
	@RequestMapping("/paidList")
	public String paidList(Model model) {
		int pageNo = getParaToInt("pageNo", 1); // 页码
		int pageSize = Globals.PAGESIZE; // 每页显示支付数
		String keyword = getParaTrim("keyword"); // 关键字
		String sellerCompanyName = getParaTrim("sellerCompanyName"); // 卖家名称
		String buyerCompanyName = getParaTrim("buyerCompanyName"); // 买家名称
		Date sdate = getParaToDate("sdate");	//开始日期
		Date edate = getParaToDate("edate");	//结束日期

		// 构造查询参数
		Map param = new HashMap();
		param.put("keyword", keyword);
		param.put("sellerCompanyName", sellerCompanyName);
		param.put("buyerCompanyName", buyerCompanyName);
		param.put("payResult", OrderPayResultEnum.SUCCESS.getValue());
		param.put("sdate", sdate);
		if (edate != null) {
			param.put("edate", DateUtils.addDays(edate, 1));
		}

		if (ContextUtil.isPurchaser()) {
			// 采购商
			List<Company> buyerCompanys = new ArrayList<>();
			buyerCompanys.add(ContextUtil.getCompany());
			List<Company> childCompanyList = companyService.findAllChildCompany(ContextUtil.getCompanyId()); // 分公司
			if (childCompanyList != null && childCompanyList.size() > 0) {
				buyerCompanys.addAll(childCompanyList);
			}
			param.put("buyerCompanys", buyerCompanys);
		} else if (ContextUtil.isProvider()) {
			param.put("sellerCompanyId", ContextUtil.getCompanyId());
		}
		PageHelper.startPage(pageNo, pageSize);
		List<Map> orderPayList = orderService.searchOrderPay(param);

		param.put("queryPrice", true);
		List<Map> priceList = orderService.searchOrderPay(param);
		double totalPrice = 0d;
		if(CollectionUtil.isNotEmpty(priceList)) {
			totalPrice = Convert.toDouble(priceList.get(0).get("totalPrice"), 0d);
		}
		model.addAttribute("totalPrice", totalPrice);		//金额总计

		model.addAttribute("orderPayList", orderPayList);
		model.addAttribute("page", new PageInfo(orderPayList));

		Map queryParam = CommonUtil.getParameterMap(request);
		model.addAttribute("queryParam", queryParam);
		model.addAttribute("CommonUtil", FreemarkerUtils.getStaticModel(CommonUtil.class));
		return "order/paidList";
	}

	/**
	 * 订单支付
	 * */
	@ResponseBody
	@RequireCompany(state = {Company.AUDIT_STATE_PASS})
	@RequestMapping(value = "/pay", method = RequestMethod.POST)
	public AjaxJson pay(PayData payData) {
		try {
			orderService.pay(payData, ContextUtil.getUser(), ContextUtil.getCurrentRole(), ContextUtil.getCompany());
			return AjaxJson.success();
		} catch (BaseException be) {
			return AjaxJson.error(be.getErrorCode());
		} catch (Exception e) {
			return AjaxJson.error("支付失败");
		}
	}

	@ResponseBody
	@RequireCompany
	@RequestMapping(value = "/checkPwd", method = RequestMethod.POST)
	public AjaxJson pay(String pwd) {
		User user = ContextUtil.getUser();
		boolean b = PasswordUtil.checkPassword(pwd, user.getSalt(), user.getPassword());
		if (!b) {
			return AjaxJson.error();
		}
		return AjaxJson.success();
	}

	@ResponseBody
	@RequestMapping("/checkPay")
	public AjaxJson checkPay() {
		Company company = companyService.getCompanyById(ContextUtil.getCompany().getId());
		if(company != null && company.getAuditState().intValue() != CompanyAuditStateEnum.PASS.getValue()) {
			if(company.getAuditState().intValue() == CompanyAuditStateEnum.BACK.getValue()) {
				return AjaxJson.error("企业资料申请被驳回，请通过之后再支付");
			} else {
				return AjaxJson.error("企业资料正在审核中，请通过之后再支付");
			}
		}
		Integer orderId = getParaToInt("orderId");
		if(orderId != null) {
			OrderPayInfo payInfo = orderService.getUnPayInfo(orderId);
			if(payInfo == null || payInfo.getTotalPrice() <= 0) {
				return AjaxJson.error("该订单不能支付");
			} else {
				return AjaxJson.success().setObj(payInfo.getId());
			}
		}
		return AjaxJson.error("操作失败");
	}

	@RequestMapping("/xieyi")
	public String xieyi() {
		return "order/xieyi";
	}

	/**
	 *	是否只是财务，不是管理员
	 * */
	private boolean isOnlyFinance() {
		if(!ContextUtil.isAdmin()) {
			List<UserEnum> userenum = new ArrayList<>();
			userenum.add(UserEnum.cfinance);
			boolean isFinance = userService.getUserAuthorityByUserId(ContextUtil.getUserId(), userenum);	//是否是财务或管理员
			return isFinance;
		}
		return false;
	}
}
